/**
 * 		Log.java
 *  Adrián E. Córdoba 		18/06/2013
 */
package ar.com.adriancordoba.app.common.log;

import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import ar.com.adriancordoba.app.common.settings.Settings;
import ar.com.adriancordoba.app.common.settings.SettingsSimpleFactory;
import ar.com.adriancordoba.app.common.settings.SettingsSimpleFactory.SettingsType;

/**
 * @author Adrián E. Córdoba
 */
public class Log {
	private static Logger logger = null;
	private final SettingsSimpleFactory settingsFactory = new SettingsSimpleFactory();
	private final Settings settings = settingsFactory.createSettings(SettingsType.XML);

	private static final String DEFAULT_LOG_FILENAME = "log";
	private static final Level DEFAULT_LOG_LEVEL = Level.ALL;
	private static final int DEFAULT_LOG_FILE_SIZE = 1048576;
	private static final int DEFAULT_MAX_LOG_FILES = 10;

	private Log() {
		// Log filename
		String logFileName = settings.getSetting("log-file-name");
		if (logFileName == null)
			logFileName = DEFAULT_LOG_FILENAME;
		// Log level
		Level level;
		String logLevel = settings.getSetting("log-level");
		if (logLevel == null)
			level = DEFAULT_LOG_LEVEL;
		else
			level = Level.parse(logLevel);
		// Log file size
		Integer logFileSize = settings.getInteger("log-file-size");
		if (logFileSize == null)
			logFileSize = DEFAULT_LOG_FILE_SIZE;
		// Maximum log files amount
		Integer maxLogFiles = settings.getInteger("max-log-files");
		if (maxLogFiles == null)
			maxLogFiles = DEFAULT_MAX_LOG_FILES;

		logger = Logger.getLogger(logFileName);
		logger.setLevel(level);
		Formatter formatter = new SimpleFormatter();
		File logDirectory = new File("Logs");
		logDirectory.mkdir();
		FileHandler fileHandler = null;
		try {
			fileHandler = new FileHandler("Logs/" + logFileName + "%g.log",
					logFileSize, maxLogFiles, true);
			fileHandler.setFormatter(formatter);
		} catch (SecurityException exception) {
			exception.printStackTrace();
		} catch (IOException exception) {
			exception.printStackTrace();
		}
		logger.addHandler(fileHandler);

	}

	public static Logger getLogger() {
		if (logger == null)
			new Log();
		return logger;
	}
}
